package com.fxp.project.jiuselu.web.models.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fxp.project.jiuselu.commons.constant.ConstantCode;
import com.fxp.project.jiuselu.commons.exceptions.JiuLuException;
import com.fxp.project.jiuselu.web.business.v1.request.cart.ReqCartAdd;
import com.fxp.project.jiuselu.web.models.goods.mapper.JslGoodsAttrMapper;
import com.fxp.project.jiuselu.web.models.goods.mapper.JslGoodsMapper;
import com.fxp.project.jiuselu.web.models.goods.vo.GoodsAttrVo;
import com.fxp.project.jiuselu.web.models.goods.vo.GoodsVo;
import com.fxp.project.jiuselu.web.models.order.entity.JslCart;
import com.fxp.project.jiuselu.web.models.order.mapper.JslCartMapper;
import com.fxp.project.jiuselu.web.models.order.service.IJslCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxp.project.jiuselu.web.models.order.vo.JslCartVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author Jason.Wang
 * @since 2021-11-11
 */
@Service
public class JslCartServiceImpl extends ServiceImpl<JslCartMapper, JslCart> implements IJslCartService {

    @Autowired
    JslCartMapper jslCartMapper;
    @Autowired
    JslGoodsMapper jslGoodsMapper;
    @Autowired
    JslGoodsAttrMapper jslGoodsAttrMapper;

    /**
     * selectJslCartVoByUserId: <br/>
     *
     * @param userId
     * @return
     * @author Kai.Wang
     * @date 2021/11/11 13:28
     */
    @Override
    public List<JslCartVo> selectJslCartVoByUserId(Long userId) {
        return jslCartMapper.selectJslCartVoByUserId(userId);
    }

    /**
     * saveJslCartByUserId: 保存商品到购物车中<br/>-
     *
     * @param
     * @return
     * @author Kai.Wang
     * @date 2021/11/11 14:10
     */
    @Override
    @Transactional
    public int saveJslCartByUserId(ReqCartAdd reqCartAdd, Long userId) {
        JslCart jslCart = new JslCart();
        jslCart.setUserId(userId);
        BeanUtils.copyProperties(reqCartAdd, jslCart);
        GoodsVo goodsVo = jslGoodsMapper.selectGoodsVoByGoodsId(reqCartAdd.getGoodsId());
        GoodsAttrVo goodsAttrVo1 = jslGoodsAttrMapper.selectGoodsAttrVoByGoodsAttrId(reqCartAdd.getAttrId());
        Integer storeCount = goodsAttrVo1.getStoreCount();
        if (null == goodsVo) {
            return 0;
        }
        if(storeCount ==0  && reqCartAdd.getType() == 0){
            throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(),"该商品暂无库存,请稍后重试");
        }
        jslCart.setGoodsName(goodsVo.getGoodsName());
        List<GoodsAttrVo> goodsAttrVo = jslGoodsAttrMapper.selectGoodsAttrVoListByGoodsId(goodsVo.getGoodsId());
        for(GoodsAttrVo g : goodsAttrVo){
            if(g.getSalePricesList().size()==0){
                throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(),"该商品暂无规格信息");
            }
        }
        if (CollectionUtils.isEmpty(goodsAttrVo)) {
            return 0;
        }
        if(reqCartAdd.getGoodsNum() > storeCount && reqCartAdd.getType() == 0){
            throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(),"超出该商品最大库存");
        }

        // 对加入购物车的产品进行信息遍历
        goodsAttrVo.forEach(attr -> {
            if (attr.getAttrId().equals(reqCartAdd.getAttrId())) {
                jslCart.setAttrName(attr.getAttrName());
                jslCart.setAttrId(attr.getAttrId());
                jslCart.setGoodsPrice(attr.getAttrPrice());
                if (!CollectionUtils.isEmpty(attr.getPartialList())) {
                    attr.getPartialList().forEach(partial -> {
                        if (partial.getPartialId().equals(reqCartAdd.getPercentId())) {
                            jslCart.setPercent(partial.getPercent());
                            jslCart.setDays(partial.getDays());
                        }
                    });
                } else {
                    jslCart.setPercent(null);
                    jslCart.setDays(null);
                }
            }
        });
        // 查询当前的商品规格在购物车中是否存在，判断产品规格，产品分期等信息是否相同
        if (null != jslCart.getId()) {
            jslCartMapper.updateById(jslCart);
        }
        QueryWrapper<JslCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", jslCart.getGoodsId())
                .eq("attr_id", jslCart.getAttrId())
                .eq("user_id", jslCart.getUserId())
                .eq("type",reqCartAdd.getType());
        if (null != jslCart.getPercent()) {
            queryWrapper.eq("percent", jslCart.getPercent());
        }
        if (null != jslCart.getDays()) {
            queryWrapper.eq("days", jslCart.getDays());
        }
        JslCart oldCart = jslCartMapper.selectOne(queryWrapper);
        if (null != oldCart) {
            jslCart.setId(oldCart.getId());
            jslCart.setGoodsNum(null != jslCart.getGoodsNum() ? oldCart.getGoodsNum() + jslCart.getGoodsNum() : oldCart.getGoodsNum() + 1);
            if(jslCart.getGoodsNum() > storeCount){
                throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(),"超出该商品最大库存");
            }
            jslCartMapper.updateById(jslCart);
        } else {
            jslCart.setCreateTime(LocalDateTime.now());
            jslCartMapper.insert(jslCart);
        }
        return 1;
    }
}
